package com.juzhencms.apps.busi.web;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.busi.service.AdminMenuService;
import com.juzhencms.apps.busi.service.AppMenuService;
import com.juzhencms.apps.busi.service.AppWeixinSourceService;
import com.juzhencms.apps.busi.service.DictionaryService;
import com.juzhencms.apps.busi.service.MenuService;
import com.juzhencms.apps.busi.service.NewsService;
import com.juzhencms.apps.busi.service.SiteService;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.HttpUtil;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;

import lombok.extern.slf4j.Slf4j;


@Controller
@RequestMapping("/appMenu")
@Slf4j
public class AppMenuController  extends BaseController{
	
	@Autowired
	private AdminMenuService adminMenuService;
	
	@Autowired
	private MenuService menuService;
	@Autowired
	private AppMenuService appMenuService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private AppWeixinSourceService appWeixinSourceService;
	
	
	@Autowired
	private SiteService siteService;
	
	
	@Autowired
	private NewsService newsService;
	
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		int site_id = 0;
		String name = "";
		
		List whereParamList=new ArrayList();
		String where=" where del_flag=0 and site_id in("+this.getUserService().getLoginUser().getSiteIds()+") ";

		
		
		if(request.getParameter("site_id")!=null && !request.getParameter("site_id").toString().trim().equals("")){
			site_id=new Integer(request.getParameter("site_id").toString());
			where+=" and site_id= ? ";
			whereParamList.add(site_id);
		}else {
			where+=" and site_id =0 ";
		}
		
	
		String sortField="position";
		String sortOrder="asc";
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,type,site_id,name,parent_id as parentId,position,publish,create_time from "+DBTable.appMenu+" "+where+" order by "+sortField+" "+sortOrder+",create_time asc", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				Date date = (Date)row.get("create_time");
				row.put("create_time",sdf.format(date));
			}
		}
		data.put("data", dataList.toArray());
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.appMenu+" where del_flag=0 and id=?",new Object[]{id});
		
		if(record!=null && record.size()>0) {
			//查找站点信息，
			int siteID=new Integer(record.get("site_id")+"");
			Map siteInfo=this.siteService.getDetail(siteID, "name");
			record.put("site_name", siteInfo.get("name")+"");
		}		
		ArrayList newsList = new ArrayList();
		ArrayList viewLimited = new ArrayList();
		if("1".equals(record.get("type")+"")) {
			if("news".equals(record.get("message_type")+"")) {
				//获取推送的文章
				if(StringUtil.isNotNullOrEmpty(record.get("weixin_source_id"))) {
					int weixin_source_id = new Integer(record.get("weixin_source_id")+"");
					newsList=this.appWeixinSourceService.getWeiXinSourceNewsList(weixin_source_id);
					
				}				
			}else if("image".equals(record.get("message_type")+"")) {
				if(StringUtil.isNotNullOrEmpty(record.get("weixin_source_id"))) {
					int weixin_source_id = new Integer(record.get("weixin_source_id")+"");
					Map imageInfo=this.appWeixinSourceService.getWeinXinImageSourceById(weixin_source_id);
					if(imageInfo!=null) {
						record.put("img", imageInfo.get("file_url"));
					}
					
				}
			}
		}else if("2".equals(record.get("type")+"")){
			if("2".equals(record.get("url_link_data")+"")) {
				if(StringUtil.isNotNullOrEmpty(record.get("weixin_source_id"))) {
					int weixin_source_id = new Integer(record.get("weixin_source_id")+"");
					viewLimited=this.appWeixinSourceService.getWeiXinSourceNewsList(weixin_source_id);
				}
			}
		}else if("3".equals(record.get("type")+"")){
			if("2".equals(record.get("url_link_data")+"")) {
				if(StringUtil.isNotNullOrEmpty(record.get("url_link_news_id"))) {
					String sql="SELECT * FROM "+DBTable.news+" where del_flag=0 and id=?";
					Map newsInfo=this.getCommonService().getJdbcDao().queryRow(sql, new Object[] {record.get("url_link_news_id")});
					if(newsInfo!=null && newsInfo.size()>0) {						
						if(StringUtil.isNotNullOrEmpty(newsInfo.get("image"))) {
							newsInfo.put("_image",Config.getUploadUrlPath()+"/"+newsInfo.get("image"));
						}else newsInfo.put("_image",Config.getUploadUrlPath()+"/nophoto.jpg");						
						viewLimited.add(newsInfo);
					}
				}
			}
		}
		record.put("newsList", newsList);
		record.put("viewLimited", viewLimited);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date) (record.get("create_time")==null?"":record.get("create_time"));
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		data.put("del_flag", 0);
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		Map result=new HashMap();
		result.put("result", 0);
		if(StringUtil.isNullOrEmpty(data.get("site_id"))) {
			result.put("msg", "参数有误，请选择正确的微信公众号");
			return WebUtil.resultString(result,request);
		}		
		if(StringUtil.isNotNullOrEmpty(data.get("type"))) {
			int  site_id=new Integer(data.get("site_id")+"");
			Map menuInfo=new HashMap();			
			menuInfo.put("name", data.get("name"));			
			menuInfo.put("type", data.get("type"));			
			menuInfo.put("parent_id", data.get("parent_id"));
            //初始化数据
			menuInfo.put("message_type", "");
			menuInfo.put("url", "");
			menuInfo.put("url_link_category_id", null);
			menuInfo.put("url_link_news_id",null);
			//menuInfo.put("url_link_category", 0);
			menuInfo.put("click_key", "");
			menuInfo.put("click_send_text", ""); 
			menuInfo.put("media_id", ""); 
			menuInfo.put("weixin_source_id", null); 
			menuInfo.put("appid","");
			menuInfo.put("pagepath", "");			
			if("1".equals(data.get("type")+"")) { //发送消息
				menuInfo.put("message_type", data.get("message_type"));
				if("news".equals(data.get("message_type")+"")) { //图文消息					
					//把当前选择的文章新增文章素材
					if(data.get("newsList")!=null) {
						List newsList = (List) data.get("newsList");					
						if(newsList!=null && newsList.size()>0) {						
							Map weiXinNews=this.appWeixinSourceService.addWeiXinNewsSource(site_id, newsList);
							String resultStr = weiXinNews.get("result")+"";
							if(weiXinNews!=null && "1".equals(resultStr)) {
								menuInfo.put("media_id", weiXinNews.get("media_id"));
								menuInfo.put("weixin_source_id", weiXinNews.get("id"));
							}else {
								result.put("result", 0);
								result.put("msg", weiXinNews.get("msg"));	
								return WebUtil.resultString(result,request); 
							}								
						}else {
							 result.put("msg", "请选择推送的文章信息");
							 return WebUtil.resultString(result,request);
						}				
				   }else {
					   result.put("msg", "请选择推送的文章信息");
					   return WebUtil.resultString(result,request);
				   }
				}else if("image".equals(data.get("message_type")+"")) {
					//处理图片消息
					if(StringUtil.isNotNullOrEmpty(data.get("img"))) {						
						Map weiXinImage=this.appWeixinSourceService.addWeinXinImageSource(site_id, data.get("img")+"",null);						
						menuInfo.put("media_id", weiXinImage.get("media_id"));
						menuInfo.put("weixin_source_id", weiXinImage.get("id"));						
					}else {
						result.put("msg", "请选择：正确的图片信息");
						return WebUtil.resultString(result,request);
					}
				}else if("text".equals(data.get("message_type")+"")){					
					//文字
					String click_key="";
				    if(StringUtil.isNotNullOrEmpty(data.get("click_key"))) {
				    	click_key=data.get("click_key")+"";
				    }else {
				    	Date datenow=new Date();
				    	click_key="TEXT_KEY_"+datenow.getTime();
				    }				    
				    menuInfo.put("click_key", click_key);
				    
				    if(StringUtil.isNotNullOrEmpty(data.get("click_send_text"))) {
				    	menuInfo.put("click_send_text", data.get("click_send_text"));
				    }else {
				    	result.put("msg", "请填写正确的回复文字");
						return WebUtil.resultString(result,request);
				    }					
				}else {
					result.put("msg", "请选择：正确的消息类型");
					return WebUtil.resultString(result,request);
				}			
			}else if("2".equals(data.get("type")+"")){ //链接跳转	
				if("0".equals(data.get("url_link_data")+"")) {
					if(StringUtil.isNotNullOrEmpty(data.get("url"))) {
						menuInfo.put("url", data.get("url"));
					}else {
						result.put("msg", "请填写正确的跳转链接");
						return WebUtil.resultString(result,request);
					}
				}else if("2".equals(data.get("url_link_data")+"")){ //文章单页
					if(data.get("viewLimited")!=null) {
						List viewLimited = (List) data.get("viewLimited");	
						if(viewLimited!=null && viewLimited.size()>0) {						
							Map weiXinNews=this.appWeixinSourceService.addWeiXinNewsSource(site_id, viewLimited);
							String resultStr = weiXinNews.get("result")+"";
							if(weiXinNews!=null && "1".equals(resultStr)) {
								menuInfo.put("media_id", weiXinNews.get("media_id"));
								menuInfo.put("weixin_source_id", weiXinNews.get("id"));
							}else {
								result.put("result", 0);
								result.put("msg", weiXinNews.get("msg"));	
								return WebUtil.resultString(result,request); 
							}								
						}else {
							result.put("msg", "请选择链接跳转的文章");
							return WebUtil.resultString(result,request);
						}						
					}else {
						result.put("msg", "请选择链接的文章");
						return WebUtil.resultString(result,request);
					}
					
					
				}else if("1".equals(data.get("url_link_data")+"")){
					if(StringUtil.isNotNullOrEmpty(data.get("url_link_category_id")) && !"0".equals(data.get("url_link_category_id")+"")) {
						menuInfo.put("url_link_category_id", data.get("url_link_category_id"));
					}else {
						result.put("msg", "请选择关联的文章分类");
						return WebUtil.resultString(result,request);
					}
				}else {
					result.put("msg", "请选择：正确的跳转URL关联数据");
					return WebUtil.resultString(result,request);
				}	
				menuInfo.put("url_link_data", data.get("url_link_data"));
				
			}else if("3".equals(data.get("type")+"")){
				menuInfo.put("appid",data.get("appid"));
				menuInfo.put("pagepath", data.get("pagepath"));
				menuInfo.put("url_link_data", data.get("url_link_data"));
				//处理备用的跳转路径				
				if("0".equals(data.get("url_link_data")+"")) {
					if(StringUtil.isNotNullOrEmpty(data.get("url"))) {
						menuInfo.put("url", data.get("url"));
					}else {
						result.put("msg", "请填写正确的跳转链接");
						return WebUtil.resultString(result,request);
					}
				}else if("2".equals(data.get("url_link_data")+"")){ //文章单页
					if(data.get("viewLimited")!=null) {
						List viewLimited = (List) data.get("viewLimited");	
						if(viewLimited!=null && viewLimited.size()>0) {							
							Map newsInfo=(Map) viewLimited.get(0);							
							String url=Config.getValue("app.domain")+"newsInfo_"+newsInfo.get("id");
							menuInfo.put("url", url);
							menuInfo.put("url_link_news_id", newsInfo.get("id"));								
						}else {
							result.put("msg", "请选择链接跳转的文章");
							return WebUtil.resultString(result,request);
						}						
					}else {
						result.put("msg", "请选择链接的文章");
						return WebUtil.resultString(result,request);
					}
				}else if("1".equals(data.get("url_link_data")+"")){
					if(StringUtil.isNotNullOrEmpty(data.get("url_link_category_id")) && !"0".equals(data.get("url_link_category_id")+"")) {
						menuInfo.put("url_link_category_id", data.get("url_link_category_id"));						
						String url=Config.getValue("app.domain")+"newsList_"+data.get("url_link_category_id")+"_page1";
						menuInfo.put("url", url);	
					}else {
						result.put("msg", "请选择关联的文章分类");
						return WebUtil.resultString(result,request);
					}
				}else {
					result.put("msg", "请选择：正确的跳转URL关联数据");
					return WebUtil.resultString(result,request);
				}	
				
				
				
				
				
			}else {				
				result.put("msg", "请选择：菜单内容");
				return WebUtil.resultString(result,request);
			}			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			if(id==null || id.equals("")){	
				menuInfo.put("site_id", site_id);
				Map prevMenu=this.getCommonService().getJdbcDao().queryRow("select position from "+DBTable.appMenu+" where del_flag=0 and parent_id=? order by position desc limit 1",new Object[]{data.get("parent_id").toString()});	
				int position = 0;
				if(prevMenu!=null) {
					 position = Integer.parseInt(prevMenu.get("position").toString());
				}
				menuInfo.put("create_time", new Date());
				menuInfo.put("position", position+1);
				menuInfo.put("create_user", this.getLoginUserId());
				this.getCommonService().getJdbcDao().addObj(DBTable.appMenu, menuInfo);
			}else{
				menuInfo.put("id", id);
				menuInfo.put("update_time", sdf.format(date));
				menuInfo.put("update_user", this.getLoginUserId());
				this.getCommonService().getJdbcDao().updateObj(DBTable.appMenu, menuInfo, "id");
			}			
		}else {
			result.put("result", 0);
			result.put("msg", "请选择：菜单内容");
		}	
		result.put("result", 1);
		result.put("msg", "保存成功");
		return WebUtil.resultString(result,request);
		
	}
	
	
	
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
	        this.getCommonService().getJdbcDao().updateSql("update "+DBTable.appMenu+" set del_flag=1,update_time=NOW() where id in ("+tmpVar+")",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		return WebUtil.resultString(result,request);
	}
	@RequestMapping(value="/getParentTreeMenuList/{site_id}/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getParentTreeMenuList(@PathVariable("site_id") String site_id,@PathVariable("id") String id,HttpServletRequest request){
		if(id==null || "".equals(id) || "undefined".equals(id)) {
			id="0";
		}
		List dataList=this.getEditParentMenuTree(new Integer(id), 0, new Integer(site_id));
		Map data=new HashMap();
		data.put("data", dataList);
		return WebUtil.resultString(data,request);
	}
	
	private List getEditParentMenuTree(int id,int pid,int siteid){
		//System.out.println(id);
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name from "+DBTable.appMenu+" where parent_id=? and site_id=? and del_flag = 0 order by position asc,id asc",new Object[]{pid,siteid});
		for(int i=0;i<dataList.size();i++){
			Map menu=(Map)dataList.get(i);
			if(menu.get("id").toString().equals(""+id)){
				menu.put("chkDisabled",true);
				//System.out.println(id);
			}else{
				List subList=this.getEditParentMenuTree(id, new Integer(menu.get("id").toString()),siteid);
				if(subList!=null && subList.size()>0)
					menu.put("children", subList);
			}
		}
		return dataList;
	}

	@RequestMapping(value="/updatePosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePosition(HttpServletRequest request){
		if(request.getParameter("position")==null || request.getParameter("id")=="")
			return "";
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.appMenu+" set position=? where id=?",new Object[]{request.getParameter("position"),request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		return WebUtil.resultString(result,request);
	}
	
	
	//拼接菜单
	@RequestMapping(value="/publishWeiXinMenu/{siteID}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String publishWeiXinMenu(@PathVariable("siteID") String siteID,HttpServletRequest request){
		Map data=new HashMap();
		//获取当前站点的
		int site_id=new Integer(siteID);
		Map result=this.appMenuService.publishWeiXinMenu(site_id);
		
		
		return WebUtil.resultString(result,request);
	}
}
